<template>
  <el-dialog class="assign-role" title="分配角色" :visible="showRoleDialog" @close="closeRoleDialog" @open="openDialog">
    <!-- 这里准备复选框 -->
    <el-checkbox-group v-model="roleIds" v-loading="isloading" >
      <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>

    <template #footer>
      <el-button type="primary" size="small" @click.native="assignRole">确定</el-button>
      <el-button size="small" @click="closeRoleDialog">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getRoleListApi } from '@/api/setting'
import { getUserStaffPhotoApi } from '@/api/user'
import { assignRoleApi } from '@/api/employees'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      roleList: [
      ],
      roleIds: [],
      isloading: false
    }
  },
  methods: {
    /**
     *
     */
    async assignRole() {
      this.$message.success('更改权限成功')
      const res = await assignRoleApi(this.userId, this.roleIds)
      this.closeRoleDialog()
    },
    /**
     * 弹框打开时获取数据
     */
    async openDialog() {
      this.isloading = true
      await this.getUserAvatar()
      await this.getRoleList()
      this.isloading = false
    },
    /**
     * 获取用户信息
     */
    async getUserAvatar() {
      const res = await getUserStaffPhotoApi(this.userId)
      const { data: { roleIds }} = res
      this.roleIds = roleIds || []
    },
    /**
     * 获取角色的方法
     */
    async getRoleList() {
      const res = await getRoleListApi(1, 999)
      const { data: { rows }} = res
      this.roleList = rows
    },
    /**
     * 关闭弹框
     */
    closeRoleDialog() {
      this.$emit('update:showRoleDialog', false)
    }
  }
}
</script>
